﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using XingFuStudio.Pioneer.Container.Interface;
using System.IO;
using System.Xml.Linq;

namespace XingFuStudio.Pioneer.Container {
    /// <summary>
    /// 持久化引擎
    /// </summary>
    public class PresistenceEngine : IDisposable{

        /// <summary>
        /// 单例对象
        /// </summary>
        private static PresistenceEngine m_Instance = null;

        /// <summary>
        /// XML存储文件夹
        /// </summary>
        private readonly string xmlFolder = String.Empty;

        /// <summary>
        /// 创建一个<see cref="SerializeEngine"/>实例
        /// </summary>
        private PresistenceEngine() {
            //初始化持久化文件路径
            this.xmlFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Persistence");
            //判断文件夹是否存在
            if (!Directory.Exists(this.xmlFolder)) {
                Directory.CreateDirectory(this.xmlFolder);
            }
        }

        /// <summary>
        /// 持久化保存
        /// </summary>
        /// <param name="pAppName">应用名称</param>
        /// <param name="data">持久化内容</param>
        public void Save(string pAppName, XElement data) {
            try {
                //判断是否实现了序列化方法
                if (data != null) {
                    //拼接持久化XML文件
                    string xmlPath = Path.Combine(this.xmlFolder, pAppName + ".xml");

                    //向持久化根中加入数据。
                    data.Save(xmlPath);
                }
            } catch {
                
            }
        }

        /// <summary>
        /// 持久化读取
        /// </summary>
        /// <param name="pAppName">应用名称</param>
        /// <returns></returns>
        public XElement Load(string pAppName) {
            XElement data = null;

            try {
                //拼接持久化XML文件
                string xmlPath = Path.Combine(this.xmlFolder, pAppName + ".xml");
                //判断文件是否存在
                if (File.Exists(xmlPath)) {
                    //读取XML文件
                    data = XElement.Load(xmlPath);
                }
            } catch {
            
            }

            return data;
        }

        /// <summary>
        /// 获取<see cref="SerializeEngine"/>类的一个单例
        /// </summary>
        /// <returns></returns>
        public static PresistenceEngine GetInstance() {
            if (m_Instance == null) {
                m_Instance = new PresistenceEngine();
            }

            return m_Instance;
        }

        #region IDisposable 成员

        /// <summary>
        /// 
        /// </summary>
        public void Dispose() {
            
        }

        #endregion
    }
}
